<template>
    <div class="container">
        <el-form :model="formData" label-width="80px" class="query-form">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="工序名称">
                        <el-input v-model="formData.ProcessName" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="工序编号">
                        <el-input v-model="formData.ProcessNumber" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="工序类型">
                        <el-input v-model="formData.ProcessType" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="产能主体" label-width="96px">
                        <el-radio-group v-model="formData.capacityBody" required>
                            <el-radio :label="false">设备</el-radio>
                            <el-radio :label="true">人员</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="负责人">
                        <el-input v-model="formData.ProcessPerson" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="添加人员">
                        <el-autocomplete
                            v-model="formData.DocumentMakers"
                            :fetch-suggestions="fetchAddedBySuggestions"
                            placeholder="请选择或输入"
                            suffix-icon="el-icon-search"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="14">
                    <el-form-item label="添加日期">
                        <el-date-picker
                            v-model="formData.FriDocumentDate"
                            type="date"
                        />
                        至
                        <el-date-picker
                            v-model="formData.EndDocumentDate"
                            type="date"
                        />
                    </el-form-item>
                </el-col>
  
                <el-col :span="6">
                    <el-form-item label=" ">
                        <el-button type="primary" @click="getdispatch">查询</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-button type="primary" @click="ExcelProduction" :loading="exportLoading">导出Excel</el-button>
            <el-button type="success" @click="handleImport" :loading="importLoading">导入Excel</el-button>
            <el-button type="danger" @click="batchDelete">批量删除</el-button>
          </el-col>
        </el-row>
        <el-table  :data="tableData" style="width: 100%; margin-top: 20px;height: 400px;" @selection-change="handleSelectionChange" ref="multipleTable">
            <el-table-column type="selection" width="55">
                <template #header>
                    <el-checkbox v-model="isAllSelected" @change="handleSelectAll"></el-checkbox>
                </template>
            </el-table-column>
            <el-table-column prop="processId" label="序号" />
            <el-table-column prop="processName" label="工序名称" />
            <el-table-column prop="processNumber" label="工序编号"  width="100px" />
            <el-table-column prop="processType" label="工序类型" width="110px" />
            <el-table-column prop="capacityBody" label="产能主体" >
                <template #default="scope">
                    {{ scope.row.capacityBody==true ? '设备' : '人员'}}
                </template>
            </el-table-column>
            <el-table-column prop="processPerson" label="负责人" width="100px" />
            <el-table-column prop="documentDate" label="制单日期" width="130px" >
                <template #default="scope">
                    {{ scope.row.documentDate ? (new Date(scope.row.documentDate).getFullYear() + '年' + String(new Date(scope.row.documentDate).getMonth() + 1).padStart(2, '0') + '月' + String(new Date(scope.row.documentDate).getDate()).padStart(2, '0') + '日') : '' }}
                </template>
            </el-table-column>
            <el-table-column prop="documentMakers" label="制单人员" />
            <el-table-column prop="remark" label="备注" width="120px" />
            <el-table-column prop="processId" label="操作" width="150px" fixed="right" >
                <template #default="scope">
                    <el-button type="danger" link @click="() => deleteItem(String(scope.row.processId))">删除</el-button>
                    <el-button type="warning" link @click="() => editItem(String(scope.row.processId))">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="demo-pagination-block">
        <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[10, 20, 30, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;">
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, nextTick } from 'vue';
  import { write, read } from '@/axios/axiosHelper';
  import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
  import router from '@/router';
  import axios from  'axios';
  
  const formData = ref({
    ProcessName:'',
    ProcessNumber:'',
    ProcessType:'',
    CapacityBody:'',
    ProcessPerson:'',
    DocumentMakers:'',
    FriDocumentDate:'',
    EndDocumentDate:'',
  });
  
  const tableData = ref([]);
  const multipleSelection = ref([]);
  const isAllSelected = ref(false);
  const exportLoading = ref(false);
  const importLoading = ref(false);
  
  onMounted(() => {
    getdispatch()
  })
  
  const page = ref({
    PageIndex: 1,
    PageSize: 50
  })
  
  const total = ref({
    totalCount: 0,
    totalPage: 0,
  })
  
  //查询显示委外数据
  const getdispatch = () => {
    read.get('w-read/api/Process/GetProcess', {
        params: {
            PageIndex: page.value.PageIndex,
            PageSize: page.value.PageSize,
            ProcessName: formData.value.ProcessName,
            ProcessNumber: formData.value.ProcessNumber,
            ProcessType: formData.value.ProcessType,
            CapacityBody: formData.value.CapacityBody,
            ProcessPerson: formData.value.ProcessPerson,
            DocumentMakers: formData.value.DocumentMakers,
            FriDocumentDate: formData.value.FriDocumentDate,
            EndDocumentDate: formData.value.EndDocumentDate,
        }
    }).then((res) => {
        tableData.value = res.data.data.list
        total.value.totalCount = res.data.data.totalCount
        total.value.totalPage = res.data.data.totalPage
        isAllSelected.value = false;
    })
  }
  
  const handleSelectionChange = (val) => {
    multipleSelection.value = val;
    isAllSelected.value = multipleSelection.value.length === tableData.value.length;
  }
  
  const handleSelectAll = (val) => {
    const table = ref(null).value;
    if (val) {
        tableData.value.forEach(row => {
            table.toggleRowSelection(row, true);
        });
    } else {
        tableData.value.forEach(row => {
            table.toggleRowSelection(row, false);
        });
    }
  }
  
  const currentPage = ref(1);
  
  const handleQuery = () => {
    // 实际调用接口获取数据逻辑
    console.log('查询参数:', formData.value);
  }
  
  const handleSizeChange = (val) => {
    page.value.PageSize = val
    getdispatch()
  }
  const handleCurrentChange = (val) => {
    page.value.PageIndex = val
    getdispatch()
  }
  
  // 自动完成建议函数（需根据实际接口实现）
  const fetchProductNameSuggestions = (query, cb) => {
    const suggestions = [];
    cb(suggestions);
  }
  
  const fetchAddedBySuggestions = (query, cb) => {
    const suggestions = [];
    cb(suggestions);
  }
  
  //导出Excel表
  const ExcelProduction = async () => {
    exportLoading.value = true;
    try {
      const response = await read.get('w-read/api/Report/ExportToExcel', {
        responseType: 'blob'
      });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'production_data.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      ElMessage.success('导出成功');
    } catch (error) {
      ElMessage.error('导出失败，请重试');
    } finally {
      exportLoading.value = false;
    }
  }
  
  //导入Excel表
  const fileInput = ref(null);
  
  const handleImport = () => {
    fileInput.value.click();
  };
  
  const handleFileChange = async (event) => {
    const files = event.target.files;
    if (files.length > 0) {
      const file = files[0];
      const formData = new FormData();
      formData.append('file', file); // 假设后端接口接收的文件参数名为 'file'
      importLoading.value = true;
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '导入中，请稍候...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        const response = await write.post('/w-write/api/Managerment/ImportExcel', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            loadingInstance.setText(`导入中: ${percentCompleted}%`);
          }
        });
        ElMessage.success('导入成功');
        getdispatch();
      } catch (error) {
        ElMessage.error('导入失败，请重试');
      } finally {
        loadingInstance.close();
        importLoading.value = false;
        // 清空输入框，以便下次选择相同文件时也能触发 change 事件
        fileInput.value.value = '';
      }
    }
  };
  
  // 单个删除方法
  const deleteItem = (id) => {
    ElMessageBox.confirm('确定要删除该条数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      write.post('w-write/api/Process/DelProcess', { ids: id })
       .then((res) => {
          if (res.data.code === 100) {
            ElMessage.success('删除成功');
            getdispatch(); // 重新获取数据
          } else {
            ElMessage.error(res.data.message);
          }
        })
       .catch((error) => {
          ElMessage.error('删除失败，请重试');
        });
    }).catch(() => {
      ElMessage.info('已取消删除');
    });
  }
  
  // 编辑方法
  const editItem = (processId) => {
    router.push({
      name: 'GetBYIdprocess', // 假设 GetOutsourcingView 页面在路由中有对应的 name
      query: {
        processId: processId
      }
    });
    console.log(processId);
  }
  
  // 批量删除方法
  const batchDelete = () => {
    if (multipleSelection.value.length === 0) {
      ElMessage.warning('请选择要删除的数据');
      return;
    }
    ElMessageBox.confirm('确定要批量删除选中的数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const ids = multipleSelection.value.map(item => item.processId).join(',');
      write.post('w-write/api/Process/DelProcess', { ids })
       .then((res) => {
          if (res.data.code === 100) {
            ElMessage.success('批量删除成功');
            getdispatch(); // 重新获取数据
          } else {
            ElMessage.error(res.data.message);
          }
        })
       .catch((error) => {
          ElMessage.error('批量删除失败，请重试');
        });
    }).catch(() => {
      ElMessage.info('已取消批量删除');
    });
  }
  </script>
  
  <style scoped>
  .query-form {
    margin-bottom: 20px;
  }
  </style>    